﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using Bookvar.ApplicationModel;
using Bookvar.ServiceModel;
using Bookvar.Common;
using Bookvar.UI.Localization;
using BookvarWpf.Properties;
using System.Threading;
using System.Diagnostics;

namespace BookvarWpf
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>

    public partial class App
    {
        protected override void OnLoadCompleted(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnLoadCompleted(e);

            if ( MainWindow.Icon == null )
            {
				//MainWindow.Icon =
				//    (ImageSource)
				//    new ImageSourceConverter().ConvertFrom( "pack://application:,,/Application.ico" );
            }
        }

        
        protected override void OnStartup(StartupEventArgs e)
        {
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            BookvarApplication.Current.ServiceLayer.AddService<IErrorReporter>(new ErrorReporter());
            BookvarApplication.Current.ServiceLayer.AddService<ILocalizationService>(new LocalizationService());

            LoadLanguage();
        }

        private static void LoadLanguage()
        {
            ILocalizationService localizationService = Current.ServiceLayer.GetService<ILocalizationService>();

            Debug.Assert(localizationService != null);
            if (localizationService == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(Settings.Default.Language))
            {
                localizationService.CurrentCulture = Thread.CurrentThread.CurrentCulture;
            }
            else
            {
                try
                {
                    localizationService.CurrentCulture = new CultureInfo(Settings.Default.Language);
                }
                catch (ArgumentException)
                {
                    localizationService.CurrentCulture = Thread.CurrentThread.CurrentCulture;
                    Settings.Default.Language = string.Empty;
                    Settings.Default.Save();
                }
            }
        }


        static void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) 
        {
            Trace.WriteLine(new string('-', 80));
            Trace.WriteLine(e.Exception.ToString());
            e.Handled = true;

            BookvarWpf.Windows.ErrorWindow errorWindow = new Windows.ErrorWindow();
            errorWindow.ErrorMessage = e.Exception.ToString();
            errorWindow.ShowDialog();
        }
    }
}